FOR LOOP

Course- Oracle/PLSQL >

This Oracle tutorial explains how to use the FOR LOOP in Oracle with syntax and examples.

Description

In Oracle, the FOR LOOP allows you to execute code repeatedly for a fixed number of times.

Syntax

The syntax for the FOR Loop in Oracle/PLSQL is:

FOR loop_counter IN [REVERSE] lowest_number..highest_number
LOOP
   {...statements...}
END LOOP;

Parameters or Arguments

loop_counter
The loop counter variable.
REVERSE
Optional. If specified, the loop counter will count in reverse.
lowest_number
The starting value for loop_counter.
highest_number
The ending value for loop_counter.
statements
The statements of code to execute each pass through the loop.

Note

  • You would use a FOR LOOP when you want to execute the loop body a fixed number of times.
  • If REVERSE is specified, then the highest_number will be the starting value for loop_counter and lowest_number will be the ending value for loop_counter.

Example

Let's look at an example of how to use a FOR LOOP in Oracle.

FOR Lcntr IN 1..20
LOOP
   LCalc := Lcntr * 31;
END LOOP;

This FOR LOOP example will loop 20 times. The counter called Lcntr will start at 1 and end at 20.

You can use the REVERSE modifier to run the FOR LOOP in reverse order. For example:

FOR Lcntr IN REVERSE 1..15
LOOP
   LCalc := Lcntr * 31;
END LOOP;

This FOR LOOP example will loop 15 times. However, because REVERSE is specified, the counter called Lcntr will start at 15 and end at 1 (in essence, looping backwards).